<template>
  <div class="admin-countries">
    <div class="header flex justify-between items-center mb-4">
      <el-button type="primary" @click="dialogVisible = true">
        创建映射列
      </el-button>
    </div>
    <!-- 搜索表单 -->
    <el-form
      ref="searchFormRef"
      :model="searchForm"
      inline
      class="search-form mb-4"
    >
      <el-form-item label="关键词" prop="keyword">
        <el-input
          v-model="searchForm.keyword"
          placeholder="请输入关键词"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item label="标准列" prop="standardId">
        <el-select
          ref="userSelectRef"
          v-model="searchForm.standardId"
          placeholder="请选择"
          filterable
          remote
          :remote-method="onKeywordInput"
          class="!w-[180px]"
          clearable
          @visible-change="onUserDropdownVisibleChange"
        >
          <el-option
            v-for="item in list"
            :key="item.id"
            :label="item.standardName"
            :value="item.id"
          />
          <template v-if="userLoading" #footer>
            <div class="text-center text-xs text-gray-500">
              <span>加载中...</span>
            </div>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="启用状态" prop="onlyEnabled">
        <el-select
          v-model="searchForm.onlyEnabled"
          placeholder="请选择"
          clearable
          class="!w-[150px]"
        >
          <el-option label="启用" :value="true" />
          <el-option label="禁用" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 国家配置列表 -->
    <el-table
      :data="tableData"
      stripe
      border
      style="width: 100%"
      show-overflow-tooltip
    >
      <el-table-column prop="id" label="ID" align="center" width="80" />
      <el-table-column
        prop="columnStandardId"
        label="标准列ID"
        align="center"
        width="140"
      />
      <el-table-column prop="originalName" align="center" label="原始列名" />
      <el-table-column prop="priority" align="center" label="优先级" />
      <el-table-column label="启用状态" align="center" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.enabled ? 'success' : 'info'">
            {{ scope.row.enabled ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="standardName" align="center" label="标准列名" />
      <el-table-column prop="columnType" align="center" label="列类型" />
      <el-table-column prop="createTime" align="center" label="创建时间" />
      <el-table-column prop="updateTime" align="center" label="更新时间" />
      <el-table-column label="操作" align="center" fixed="right" width="120">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            link
            @click="editStandardColumn(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            link
            @click="deleteCountry(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      class="mt-4"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      :page-sizes="[20, 40, 60]"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />

    <!-- 新增/编辑国家对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑列' : '新增列'"
      width="500px"
      @close="close"
    >
      <el-form
        ref="countryFormRef"
        :model="countryForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="原名" prop="originalName">
          <el-input
            v-model="countryForm.originalName"
            placeholder="请输入原名"
          />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number
            v-model="countryForm.priority"
            placeholder="请输入优先级"
            :step="1"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="启用状态" prop="enabled">
          <el-switch
            v-model="countryForm.enabled"
            :active-value="true"
            :inactive-value="false"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoad" @click="submitCountry">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  getAllColumnMap,
  deleteColumnwMap,
  createColumnMap,
  updateColumnMap
} from "@/api/adminColumnMapApi";

import { useRemotePagedSelect } from "@/composables/useRemotePagedSelect";
import { colSelectFetcher, type ColItem } from "@/composables/colSelectFetcher";
import { type ElSelect } from "element-plus";

// 用户下拉：远程搜索 + 触底加载
const {
  list,
  loading: userLoading,
  onKeywordInput,
  onDropdownScroll
} = useRemotePagedSelect<ColItem>({
  pageSize: 20,
  autoLoad: true,
  debounceMs: 300,
  fetcher: colSelectFetcher
});

const userSelectRef = ref<InstanceType<typeof ElSelect> | null>(null);
let userDropdownWrapEl: HTMLElement | null = null;

function onUserDropdownVisibleChange(visible: boolean) {
  if (visible) {
    nextTick(() => {
      const popperEl = userSelectRef.value?.popperRef as
        | HTMLElement
        | undefined;
      // 在该选择器自己的 popper 里找 wrap
      userDropdownWrapEl =
        popperEl?.querySelector(".el-select-dropdown__wrap") ?? null;
      userDropdownWrapEl?.addEventListener("scroll", onDropdownScroll, {
        passive: true
      });
    });
  } else {
    userDropdownWrapEl?.removeEventListener("scroll", onDropdownScroll);
    userDropdownWrapEl = null;
  }
}

// 搜索表单数据
const searchForm = reactive({
  keyword: "",
  standardId: "",
  onlyEnabled: true
});
const searchFormRef = ref();
const options = ref([]);
// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
});

// 表格数据
const tableData = ref<any[]>([]);

// 获取所有国家配置数据
const fetchCountries = async () => {
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...searchForm
    };
    const { success, data, message } = await getAllColumnMap(params);
    if (success) {
      const { records, total, size, current } = data;
      tableData.value = records;
      pagination.total = total;
      pagination.pageSize = size;
      pagination.currentPage = current;
    } else {
      ElMessage.error(message);
    }
  } catch (error) {
    console.error(error);
  }
};

const onSearch = () => {
  pagination.currentPage = 1;
  fetchCountries();
};

const onReset = () => {
  searchForm.keyword = "";
  searchForm.onlyEnabled = true;
  pagination.currentPage = 1;
  fetchCountries();
};

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  fetchCountries();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchCountries();
};

// 新增/编辑对话框相关
const dialogVisible = ref(false);
type FormType = {
  id?: number | string;
  priority?: number;
  originalName?: string;
  enabled?: boolean;
};
const countryForm = reactive<FormType>({
  originalName: "",
  priority: 1,
  enabled: true
});
const countryFormRef = ref<FormInstance>();

const rules: FormRules = {
  originalName: [{ required: true, message: "请输入原名", trigger: "blur" }],
  priority: [{ required: true, message: "请输入优先级", trigger: "blur" }],
  enabled: [{ required: true, message: "请选择是否启用", trigger: "blur" }]
};

// 新增国家
const close = async () => {
  countryFormRef.value?.resetFields();
  countryFormRef.value?.clearValidate();
};
const isEdit = computed(() => !!countryForm?.id);
const submitLoad = ref(false);
const submitCountry = async () => {
  countryFormRef.value?.validate(async valid => {
    if (valid) {
      try {
        submitLoad.value = true;
        if (isEdit.value) {
          await updateColumnMap(countryForm);
        } else {
          await createColumnMap(countryForm);
        }
        ElMessage.success(isEdit.value ? "编辑成功" : "新增成功");
        dialogVisible.value = false;
        fetchCountries();
      } finally {
        submitLoad.value = false;
      }
    }
  });
};

const deleteCountry = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定删除映射列【${row.originalName}】吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );
    await deleteColumnwMap(row.id);
    ElMessage.success("删除成功");
    fetchCountries();
  } catch (error) {
    ElMessage.info("已取消删除");
  }
};

const editStandardColumn = async (row: any) => {
  const { id, priority, originalName, enabled } = row;
  countryForm.id = id;
  countryForm.priority = priority;
  countryForm.originalName = originalName;
  countryForm.enabled = enabled;
  dialogVisible.value = true;
};
onMounted(() => {
  fetchCountries();
});
</script>

<style scoped>
.admin-countries {
  padding: 20px;
  background-color: #fff;
  .el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }
}
.header h2 {
  font-size: 20px;
  font-weight: bold;
}
</style>
